package com.atguigu.gmall.receiver;


import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeifnClient;
import com.atguigu.gmall.payment.service.PaymentService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * ClassName: PaymentReceiver
 * Package: com.atguigu.gmall.receiver
 * Description:
 *
 * @Author 刘轩
 * @Create 2023-09-09 9:25
 * @Version 1.0
 */
// orderinfo 发送消息  paymentInfo 监听消息
@Component
@Slf4j
public class PaymentReceiver {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderFeifnClient orderFeifnClient;

    /**
     * 监听消息---rabbitmq -- 消息不丢失 消息挤压 幂等性
     *
     * @param orderId
     * @param message
     * @param channel
     */

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_CLOSE, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_CLOSE),
            key = {MqConst.ROUTING_PAYMENT_CLOSE}
    ))
    public void paymentClose(Long orderId, Message message, Channel channel) throws IOException {
        try {
            // 判断 orderId
            if (orderId != null) {
                OrderInfo orderInfo = orderFeifnClient.getOrderInfo(orderId);
                if (orderInfo != null) {
                    // 获取paymentInfo； 利用业务字段 field 判断
                    PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(orderInfo.getOutTradeNo(), PaymentType.ALIPAY.name());
                    // 交易记录状态
                    if (null != paymentInfoQuery && !"CLOSED".equals(paymentInfoQuery.getPaymentStatus())) {
                        paymentService.closePayment(paymentInfoQuery.getId());
                    }
                }

            }
        } catch (Exception e) {
            // 记录消息 insert into msg values(???);
            log.error(orderId+"关闭交易记录失败");
            e.printStackTrace();
        }
        // 手动签收
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
